package com.huqi.controller;

import com.google.common.base.Preconditions;
import com.huqi.beanutils.ModelUtil;
import com.huqi.cache.CacheUtil;
import com.huqi.controller.vo.HttpReqVO;
import com.huqi.date.DateUtil;
import com.huqi.httpmianshidemo.model.HttpService.HttpReqModel;
import com.huqi.httpmianshidemo.model.common.WebResult;
import com.huqi.result.ResultUtil;
import com.huqi.servier.HttpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.UUID;

/**
 * @author 胡琦
 * @date 2021-07-24 星期六 15:07
 */
@Controller
@RequestMapping("/httpController")
public class HttpController {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpController.class);

    @Autowired
    private HttpService httpService;

    /**
     * 扣款http接口
     * @param reqVO 入参
     * @return
     */
    @RequestMapping(value = "/deductions.json", method = RequestMethod.POST)
    @ResponseBody
    public WebResult deductions(@RequestBody HttpReqVO reqVO) throws IllegalAccessException {
        Preconditions.checkArgument(reqVO != null, "request 不能为空");
        reqVO.check();
        checkKey(reqVO.getRequestKey());
        String result = httpService.deductions(ModelUtil.dtoToModel(reqVO, HttpReqModel.class));
        return ResultUtil.success(result);
    }

    @RequestMapping(value = "/getKey.json", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public WebResult getKey() {
        // 生成一个UUID当作key
        return ResultUtil.success(new StringBuilder(UUID.randomUUID().toString())
                .append("-")
                .append(DateUtil.getDateStringFormat(new Date(), "yyyy-MM-dd-HH-mm-ss"))
                .toString());
    }

    /**
     * 校验幂等key
     * @return
     */
    private void checkKey(String key) throws IllegalAccessException {
        // 将此key存入redis中
        boolean exit = CacheUtil.setNX(key, key, 1);
        if (!exit) {
            throw new IllegalAccessException("key已经存在,幂等校验不通过...");
        }
    }

}

